package com.ysb.corrector.hmm;

import com.alibaba.fastjson.JSONObject;
import com.ysb.common.PathUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @author husc
 * @date 2021/3/16
 */
public class DefaultHmmParams implements AbstractHmmParams{
    private static final String DATA = "data";
    private static final String DEFAULT = "default";
    private final JSONObject startDict = PathUtils.readJsonFile(PathUtils.HMM_START_JSON_PATH);
    private final JSONObject emissionDict = PathUtils.readJsonFile(PathUtils.HMM_EMISSION_JSON_PATH);
    private final JSONObject transitionDict = PathUtils.readJsonFile(PathUtils.HMM_TRANSITION_JSON_PATH);
    private final JSONObject py2hzDict = PathUtils.readJsonFile(PathUtils.HMM_PY2HZ_JSON_PATH);

    /**
     * @param state 状态，即：汉字
     */
    @Override
    public float initialProbability(String state) {
        JSONObject data = startDict.getJSONObject(DATA);
        float defaultValue = startDict.getFloatValue(DEFAULT);
        float prob = data.containsKey(state) ? data.getFloatValue(state) : defaultValue;
        return prob;
    }

    /**
     * @param state       状态，即：汉字
     * @param observation 观测值，即：拼音
     */
    @Override
    public float emission(String state, String observation) {
        JSONObject data = emissionDict.getJSONObject(DATA);
        float defaultValue = emissionDict.getFloatValue(DEFAULT);
        if (data.containsKey(state)) {
            JSONObject probDict = data.getJSONObject(state);
            if (probDict.containsKey(observation)) {
                return probDict.getFloatValue(observation);
            } else {
                return defaultValue;
            }
        } else {
            return defaultValue;
        }
    }

    /**
     * @param fromState 前一个汉字
     * @param toState   相邻的后一个汉字
     */
    @Override
    public float transition(String fromState, String toState) {
        JSONObject data = transitionDict.getJSONObject(DATA);
        float defaultValue = transitionDict.getFloatValue(DEFAULT);
        if (data.containsKey(fromState)) {
            JSONObject probDict = data.getJSONObject(fromState);
            if (probDict.containsKey(toState)) {
                return probDict.getFloatValue(toState);
            } else {
                return defaultValue;
            }
        } else {
            return defaultValue;
        }
    }

    /**
     * @param observation 观测值
     */
    @Override
    public List<String> getStates(String observation) {
        String hanzi = py2hzDict.getString(observation);
        char[] chars = hanzi.toCharArray();
        List<String> hanziList = new ArrayList<String>(chars.length);
        for (char aChar : chars) {
            hanziList.add(String.valueOf(aChar));
        }
        return hanziList;
    }

}
